package scuts.flash;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import scuts.core.types.Either;
import scuts.core.types.ProgressiveFuture;

/**
 * ...
 * @author 
 */

enum LoadError {
  Err(msg:String);
}
 
class LoaderExtensions 
{

  public static function loadBitmapData(url:URLRequest):Future<Either<LoadError, BitmapData>> 
  {
    var l = new Loader();
    
    var fut = new ProgressiveFuture();
    
    var onComplete = null;
    var onProgress = null;
    var onError = null;
    
    function removeListeners() {
      l.loaderInfo.removeEventListener(onComplete);
      l.loaderInfo.removeEventListener(onError);
      l.loaderInfo.removeEventListener(onProgress);
    }
    
    function onError (e:ErrorEvent) {
      fut.setValue(Left(e));
      removeListeners();
    }
    
    function onComplete (e:Event) {
      var bitmap:Bitmap = cast e.target.content;
      
      fut.setValue(Right(bitmap.bitmapData));
      
      removeListeners();
    }
    
    function onProgress(e:ProgressEvent) {
      fut.setProgress(e.bytesLoaded/e.bytesTotal);
    }
    
    l.loaderInfo.addEventListener(Event.COMPLETE, onComplete);
    l.loaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
    l.loaderInfo.addEventListener(ErrorEvent.ERROR, onError);
    l.load(url);
    
    return fut;
  }
  
}